package com.my.socket.nio.v22;

import com.google.common.base.Throwables;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Created by ZhongGang
 * at 2018/7/4 18:01
 */
public class Client {
    private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        List<Future<?>> futures = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            futures.add(executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try (Socket socket = new Socket()) {
                        socket.connect(new InetSocketAddress("127.0.0.1", 9999));
                        LOGGER.info("connect: {}", socket);

                        OutputStream outputStream = socket.getOutputStream();
                        IOUtils.write("I am Alex Zhong", outputStream, "UTF-8");
                        socket.shutdownOutput();

                        InputStream inputStream = socket.getInputStream();
                        String response = IOUtils.toString(inputStream, "UTF-8");
                        socket.shutdownInput();
                        LOGGER.info("read: {}", response);
                    } catch (Exception e) {
                        LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
                    }
                }
            }));
        }

        for (Future<?> future : futures) {
            future.get();
        }

        LOGGER.info("it takes {} second(s)", (System.currentTimeMillis() - start) / 1000.00);
        executorService.shutdownNow();
    }
}
